<template>
  <div class="divBox">
    <el-card class="box-card">
      <!-- 搜索总商户 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="商户名称">
          <el-input v-model="searchForm.mer_name" placeholder="请输入商户名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="联系人">
          <el-input v-model="searchForm.real_name" placeholder="请输入联系人" clearable></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchForm.mer_phone" placeholder="请输入手机号" clearable></el-input>
        </el-form-item>
        <el-form-item label="关键字">
          <el-input v-model="searchForm.mer_keyword" placeholder="请输入关键字" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 总商户列表 -->
      <el-table
        v-loading="tableLoading"
        :data="tableData"
        border
        style="width: 100%">
        <el-table-column
          prop="mer_id"
          label="商户ID"
          width="80">
        </el-table-column>
        <el-table-column
          prop="mer_avatar"
          label="Logo"
          width="80">
          <template slot-scope="scope">
            <el-image
              style="width: 40px; height: 40px"
              :src="scope.row.mer_avatar"
              fit="cover"
              :preview-src-list="[scope.row.mer_avatar]">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column
          prop="mer_name"
          label="商户名称"
          min-width="120">
        </el-table-column>
        <el-table-column
          prop="real_name"
          label="联系人"
          width="100">
        </el-table-column>
        <el-table-column
          prop="mer_keyword"
          label="关键字"
          width="120">
        </el-table-column>
        <el-table-column
          prop="mer_phone"
          label="联系电话"
          width="120">
        </el-table-column>
        <el-table-column
          prop="mer_address"
          label="商户地址"
          min-width="200">
        </el-table-column>
        <el-table-column
          label="操作"
          width="120"
          fixed="right">
          <template slot-scope="scope">
            <!-- 根据不同条件显示不同按钮 -->
            <el-button
              v-if="is_mer_id !== scope.row.mer_id || (is_mer_id === scope.row.mer_id && is_conduct !== 2 && is_conduct !== 0)"
              type="text"
              size="small"
              @click="handleApplySubMerchant(scope.row)">
              申请成为代理商
            </el-button>
            <el-button
              v-if="is_mer_id === scope.row.mer_id && is_conduct === 2"
              type="text"
              size="small"
              @click="handleCancelApply(scope.row)">
              取消当前申请
            </el-button>
            <el-button
              v-if="is_mer_id === scope.row.mer_id && is_conduct === 0"
              type="text"
              size="small"
              @click="handleCancelRelation(scope.row)">
              取消当前关联
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getMerchantList, updateMerchantId, updateMerchantConduct, updateMerchantStatus } from '@/api/merchant'
import { getBaseInfo } from "@/api/user";

export default {
  name: 'MerchantApplication',
  data() {
    // 手机号验证规则
    const validatePhone = (rule, value, callback) => {
      if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }
    return {
      mer_id: '',
      is_conduct: '',
      is_mer_id: '',
      is_status: '',
      // 搜索表单
      searchForm: {
        mer_name: '',
        real_name: '',
        mer_phone: '',
        mer_keyword: ''
      },
      // 表格数据
      tableLoading: false,
      tableData: [],
      page: 1,
      limit: 10,
      total: 0,
    }
  },
  created() {
    this.getMainMerchantList()
    // 获取当前登录商户信息
    getBaseInfo().then(res => {
      this.mer_id = res.data.mer_id;
      this.is_conduct = res.data.is_conduct;
      this.is_mer_id = res.data.is_mer_id;
      this.is_status = res.data.is_status;
      console.log('当前登录商户ID:', this.mer_id);
      console.log('商户状态信息:', {
        is_conduct: this.is_conduct,
        is_mer_id: this.is_mer_id,
        is_status: this.is_status
      });
    }).catch(err => {
      this.$message.error('获取商户信息失败');
    });
  },
  methods: {
    // 获取总商户列表
    async getMainMerchantList() {
      this.tableLoading = true
      try {
        const params = {
          page: this.page,
          limit: this.limit,
          is_status: 1,
          ...this.searchForm
        }
        const res = await getMerchantList(params)
        if (res.status === 200) {
          this.tableData = res.data.list
          this.total = res.data.count
        } else {
          this.$message.error(res.msg || '获取数据失败')
        }
      } catch (error) {
        console.error('获取商户列表失败:', error)
        this.$message.error('获取数据失败')
      } finally {
        this.tableLoading = false
      }
    },
    // 搜索
    handleSearch() {
      this.page = 1
      console.log(this.searchForm,'searchForm');
      
      this.getMainMerchantList()
    },
    // 重置搜索
    resetSearch() {
      this.searchForm = {
        mer_name: '',
        real_name: '',
        mer_phone: '',
        mer_keyword: ''
      }
      this.handleSearch()
    },
    // 分页
    handleSizeChange(val) {
      this.limit = val
      this.getMainMerchantList()
    },
    handleCurrentChange(val) {
      this.page = val
      this.getMainMerchantList()
    },
    // 申请子商户
    handleApplySubMerchant(row) {
      // 先刷新一次商户信息，确保状态是最新的
      this.refreshMerchantInfo().then(() => {
        // 先判断当前商户是否已经是总商户
        if (this.is_status === 1) {
          this.$message.warning('您目前为代理商，不能再关联代理商');
          return;
        }
        
        // 判断是否正在申请总商户
        if (this.is_conduct === 1) {
          this.$message.warning('您目前正在申请代理商，请先取消申请再操作');
          return;
        }
        
        // 判断是否正在申请子商户
        if (this.is_conduct === 2) {
          this.$message.warning('您目前正在申请代理商，请先取消申请再操作');
          return;
        }
        
        this.$confirm(`确定要申请成为${row.mer_name}的代理商吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          console.log(this.mer_id,'mer_id');
          
          // 1. 调用更新商户关联ID的API
          updateMerchantId(this.mer_id, {
            is_mer_id: row.mer_id
          }).then(res => {
            if (res.status === 200) {
              // 2. 调用更新商户申请状态的API
              return updateMerchantConduct(this.mer_id, {
                is_conduct: 2  // 申请子商户状态为2
              });
            } else {
              return Promise.reject(res);
            }
          }).then(res => {
            if (res.status === 200) {
              this.$message.success('申请提交成功');
              // 刷新当前商户信息
              this.refreshMerchantInfo();
            } else {
              this.$message.error(res.msg || '申请提交失败');
            }
          }).catch(err => {
            this.$message.error(err.msg || '申请提交失败');
          });
        }).catch(() => {
          this.$message.info('已取消申请');
        });
      }).catch(() => {
        this.$message.error('刷新商户信息失败');
      });
    },
    // 刷新商户信息
    refreshMerchantInfo() {
      return getBaseInfo().then(res => {
        this.mer_id = res.data.mer_id;
        this.is_conduct = res.data.is_conduct;
        this.is_mer_id = res.data.is_mer_id;
        this.is_status = res.data.is_status;
        return Promise.resolve(res.data);
      }).catch(err => {
        this.$message.error('获取商户信息失败');
        return Promise.reject(err);
      });
    },
    // 取消当前申请
    handleCancelApply(row) {
      this.$confirm('确定要取消申请吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用更新商户申请状态的API
        updateMerchantConduct(this.mer_id, {
          is_conduct: 0 // 取消申请状态
        }).then(res => {
          if (res.status === 200) {
            // 同时调用更新商户关联ID的API
            return updateMerchantId(this.mer_id, {
              is_mer_id: 0 // 取消关联，设置为0
            });
          } else {
            return Promise.reject(res);
          }
        }).then(res => {
          if (res.status === 200) {
            this.$message.success('取消申请成功');
            // 刷新当前商户信息
            this.refreshMerchantInfo();
          } else {
            this.$message.error(res.msg || '取消申请失败');
          }
        }).catch(err => {
          this.$message.error(err.msg || '取消申请失败');
        });
      }).catch(() => {
        this.$message.info('已取消操作');
      });
    },
    
    // 取消当前关联
    handleCancelRelation(row) {
      this.$confirm('确定要取消关联吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用更新商户关联ID的API
        updateMerchantId(this.mer_id, {
          is_mer_id: 0 // 取消关联，设置为0
        }).then(res => {
          if (res.status === 200) {
            // 调用更新商户申请状态的API
            return updateMerchantConduct(this.mer_id, {
              is_conduct: 0 // 取消申请状态
            });
          } else {
            return Promise.reject(res);
          }
        }).then(res => {
          if (res.status === 200) {
            // 调用更新商户状态的API
            return updateMerchantStatus(this.mer_id, {
              is_status: 0 // 设置状态为0
            });
          } else {
            return Promise.reject(res);
          }
        }).then(res => {
          if (res.status === 200) {
            this.$message.success('取消关联成功');
            // 刷新当前商户信息
            this.refreshMerchantInfo();
          } else {
            this.$message.error(res.msg || '取消关联失败');
          }
        }).catch(err => {
          this.$message.error(err.msg || '取消关联失败');
        });
      }).catch(() => {
        this.$message.info('已取消操作');
      });
    },
  }
}
</script>

<style lang="scss" scoped>
.search-form {
  margin-bottom: 20px;
}
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
